//
//  WJLocationManager.m
//  ows
//
//  Created by 王军 on 2017/9/2.
//  Copyright © 2017年 ows. All rights reserved.
//
/***
 定位工具.
 1.获取城市，坐标等。
 ***/

#import "WJLocationManager.h"
#import "CoreLocation/CoreLocation.h"
#include <objc/objc.h>
#include <objc/runtime.h>
#import "WJCommonUtils.h"

@interface WJLocationManager()<CLLocationManagerDelegate>

@property(strong, nonatomic) CLLocationManager *locationManager;

@end

@implementation WJLocationManager

+(WJLocationManager *)shareInstance{
    static WJLocationManager *r_rootInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        r_rootInstance = [[WJLocationManager alloc] init];
        [r_rootInstance initOptions];
    });
    return r_rootInstance;
}

-(void)initOptions{
    
}

-(void)fetchCurrentCity{
    // 获取当前位置的坐标.
    if ([CLLocationManager locationServicesEnabled]) {//判断定位操作是否被允许
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;//遵循代理
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 10.0f;
        [self.locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8以上版本定位需要）
        [self.locationManager startUpdatingLocation];//开始定位
    }else{//不能定位用户的位置的情况再次进行判断，并给与用户提示
        //1.提醒用户检查当前的网络状况
        //2.提醒用户打开定位开关
    }
}

// 获取地理信息，包括城市信息.
-(void)fetchLocationInfoSuccess:(void (^)(id result))success fail:(void (^)(id result))fail {
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        fail(@"请开启定位用于获取天气信息");
        return;
    }
    objc_setAssociatedObject(self, "fetchLocationInfo_success", [success copy],
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, "fetchLocationInfo_fail", [fail copy],
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if ([CLLocationManager locationServicesEnabled]) {
        if (self.locationManager) {
            [self.locationManager stopUpdatingLocation];
            self.locationManager = nil;
        }
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 10.0f;
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }else{
        fail([[NSMutableDictionary alloc] initWithObjectsAndKeys:
              @"-1",@"code",
              @"定位失败，没开启",@"message",
              nil]);
    }
}

#pragma mark -- CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *currLocation = [locations lastObject];
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([WJCommonUtils isSIMULATOR]) {
            NSMutableDictionary *info = [NSMutableDictionary new];
            info[@"Country"] = @"";
            info[@"State"] = @"";
            info[@"City"] = @"上海市";
            info[@"CLLocation"] = currLocation;
            void (^success)(id info) = objc_getAssociatedObject(self, "fetchLocationInfo_success");
            if (success){
                if (self.locationManager) {
                    [self.locationManager stopUpdatingLocation];
                    self.locationManager = nil;
                }
                success(info);
            }
            return;
        }
        for (CLPlacemark * placemark in placemarks) {
            NSDictionary *address = [placemark addressDictionary];
            NSMutableString *mStr = [NSMutableString new];
            if (![WJCommonUtils isBlankString:[address objectForKey:@"State"]]) {
                [mStr appendString:[address objectForKey:@"State"]];
                [mStr appendString:@" "];
            }
            if (![WJCommonUtils isBlankString:[address objectForKey:@"City"]]) {
                [mStr appendString:[address objectForKey:@"City"]];
                [mStr appendString:@" "];
            }
            if (![WJCommonUtils isBlankString:[address objectForKey:@"SubLocality"]]) {
                [mStr appendString:[address objectForKey:@"SubLocality"]];
                [mStr appendString:@" "];
            }
            if (![WJCommonUtils isBlankString:[address objectForKey:@"Name"]]) {
                [mStr appendString:[address objectForKey:@"Name"]];
                [mStr appendString:@" "];
            }
            self.addressStr = [NSString stringWithString:mStr];
            NSMutableDictionary *info = [NSMutableDictionary new];
            info[@"Country"] = [address objectForKey:@"Country"];
            info[@"State"] = [address objectForKey:@"State"];
            info[@"City"] = [address objectForKey:@"City"];
            info[@"CLLocation"] = currLocation;
            void (^success)(id info) = objc_getAssociatedObject(self, "fetchLocationInfo_success");
            if (success){
                if (self.locationManager) {
                    [self.locationManager stopUpdatingLocation];
                    self.locationManager = nil;
                }
                success(info);
            }
            break;
        }
    }];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if ([error code] == kCLErrorDenied){
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
    void (^fail)(id info) = objc_getAssociatedObject(self, "fetchLocationInfo_fail");
    if (fail){
        fail([[NSMutableDictionary alloc] initWithObjectsAndKeys:
              @"-1",@"code",
              error.domain,@"message",
              nil]);
    }
}

@end
